package tomoto.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class XMLResourceBundleControl extends ResourceBundle.Control {
	private static XMLResourceBundleControl instance = new XMLResourceBundleControl();
	
	public static XMLResourceBundleControl getInstance() {
		return instance;
	}
	
	private XMLResourceBundleControl() {
		
	}
	
	@Override
	public List<String> getFormats(String baseName) {
		return Collections.singletonList("xml");
	}

	@Override
	public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
			throws IllegalAccessException, InstantiationException, IOException {
		String resourceName = toResourceName(toBundleName(baseName, locale), format);
		InputStream in = null;
		if (reload) {
			URL url = loader.getResource(resourceName);
			if (url != null) {
				URLConnection conn = url.openConnection();
				if (conn != null) {
					conn.setUseCaches(false);
					in = conn.getInputStream();
				}
			}
		} else {
			in = loader.getResourceAsStream(resourceName);
		}

		if (in != null) {
			return new XMLResourceBundle(new BufferedInputStream(in));
		} else {
			return null;
		}
	}
}
